<?php

// Namespace

namespace Snsfg;


// Dependencies

require_once(PATH_APPLICATION . 'Class/ISocialNetworkDriver.php');
require_once(PATH_APPLICATION . 'Component/Wechat/Wechat.php');

require_once(PATH_APPLICATION . 'Model/CAccount.php');
require_once(PATH_APPLICATION . 'Model/CPostStatus.php');
require_once(PATH_APPLICATION . 'Model/CSnsUser.php');
require_once(PATH_APPLICATION . 'Model/CMedia.php');


//require_once(PATH_APPLICATION . 'Component/php/SocketLog.class.php');


/**
 *
 * @package		Gt_Sync
 * @category	Driver
 */

class CWechatDriver implements ISocialNetworkDriver
{

	/**
	 *
	 */

	public function completeConnection(&$account)
	{
	}


	/**
	 *
	 */

	public function connectDriver($params = null)
	{
	}


	/**
	 *
	 */

	public function disconnect(&$account)
	{
		$appId = $account->getWechatAppId();

		return array('appId'=>$appId, 'description' => 'disconnected');
	}



	public function getGroups(&$account)
	{
		// $token_expired = ( time() - ($account->getUpdateTime() + 7200) );


		$accessToken = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());


		$responseJson = $accessToken->getAccessToken();
		$accessToken = json_decode($responseJson, true);

		$wechat = new \Wechat($accessToken['access_token']);

		$groups = $wechat->callapi('groups/get');
		
//$groups = urldecode(json_encode($groups));
		return $groups;
	}



	/**
	 *
	 */

	public function getSnsUsers(&$account)
	{
		// $token_expired = ( time() - ($account->getUpdateTime() + 7200) );


		$accessToken = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());

		$responseJson = $accessToken->getAccessToken();
		$accessToken = json_decode($responseJson, true);

		$wechat = new \Wechat($accessToken['access_token']);

		$openIds = $wechat->callapi('user/get');
		
		if(is_array($openIds) && !empty($openIds))
		{
			$SnsUser = new CSnsUser();

			$rawUserInfos = array();

			foreach($openIds['data']['openid'] as $openId) {

				$rawUserInfo = $this->getSnsUserInfo($account, $openId);
				$rawUserInfos[] = $rawUserInfo;

				$rawSnsUsers = $SnsUser->find
				(
					array
					(
						'conditions' => array
						(
							'openId' => array(EQUAL, $rawUserInfo['openid'])
						)
					)
				);

				$paramsForGroup = array('openid' => $rawUserInfo['openid']);
				$groupId = $wechat->callapi('groups/getid', $paramsForGroup, 'POST');

				if(!count($rawSnsUsers) == 0) {
					$rawSnsUser = array_shift($rawSnsUsers);
					$SnsUser->loadFromRawObject($rawSnsUser);
				}

				$SnsUser->setSocialNetwork(SOCIAL_NETWORK_WECHAT);
				$SnsUser->setWechatAccount($account->getWechatAppId());
				$SnsUser->setSubscribe($rawUserInfo['subscribe']);
				$SnsUser->setOpenId($rawUserInfo['openid']);
				$SnsUser->setNickname($rawUserInfo['nickname']);
				$SnsUser->setSex($rawUserInfo['sex']);
				$SnsUser->setCity($rawUserInfo['city']);
				$SnsUser->setCountry($rawUserInfo['country']);
				$SnsUser->setProvince($rawUserInfo['province']);
				$SnsUser->setLanguage($rawUserInfo['language']);
				$SnsUser->setHeadImgUrl($rawUserInfo['headimgurl']);
				$SnsUser->setSubscribeTime($rawUserInfo['subscribe_time']);
				
				if(isset($rawUserInfo['unionid'])) {
					$SnsUser->setUnionId($rawUserInfo['unionid']);
				}

				if(isset($rawUserInfo['remark'])) {
					$SnsUser->setUnionId($rawUserInfo['remark']);
				}

				if($groupId['groupid']) {
					$SnsUser->setGroupId($groupId['groupid']);
				}

				$SnsUser->save();
				$SnsUser->reset();
			}
		}
		
		return $rawUserInfos;

		// return $openIds;
	}


	/**
	 *
	 */

	public function getSnsUserInfo(&$account, $openId)
	{
		// $token_expired = ( time() - ($account->getUpdateTime() + 7200) );


		$accessToken = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());

		$responseJson = $accessToken->getAccessToken();
		$accessToken = json_decode($responseJson, true);

		$params = array('openid' => $openId);

		$wechat = new \Wechat($accessToken['access_token']);

		$userinfo = $wechat->callapi('user/info', $params);
		
//$groups = urldecode(json_encode($groups));
		return $userinfo;
	}


	/**
	 *
	 */

	public function postStatus(&$account, $messageData)
	{
		$payload = $messageData['payload'];

		// slog('payload in CWechatDriver postStatus');
		// slog($payload);

		$accessToken = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());
		$responseJson = $accessToken->getAccessToken();
		$accessToken = json_decode($responseJson, true);

		$wechat = new \Wechat($accessToken['access_token']);

		$params = array(
				    'filter' => array('group_id' => $payload['group_id']),
				    'msgtype' => $payload['msgtype']
			    );

		switch ($payload['msgtype']) {
			case 'text':
				$params['text'] = array('content' => urlencode($payload['content']));
				break;
			case 'mpnews':
				$media = new CMedia();

				$articles = $payload['articles'];

				foreach ($articles as $key => $article) {
					
					$article['content'] = $article['content'];
				}

				$paramsArticles = $this->prepareNews($articles, $account);

				
				// slog('Prepare mpnews:');
				// slog($paramsArticles);

				
				$uploadInfo = $wechat->uploadNews($paramsArticles);
				$uploadInfo = json_decode($uploadInfo, true);

				if(isset($uploadInfo['errcode']) && $uploadInfo['errcode'] != 0)
				{
					$result = $uploadInfo;

					return 'Upload news:'.json_encode($result);
				}
				$media->setType($payload['msgtype']);
				$media->setMediaId($uploadInfo['media_id']);
				$media->setCreateTime($uploadInfo['created_at']);
				$media->save();

				$params['mpnews'] = array('media_id'=>$uploadInfo['media_id']);

				break;
			case 'voice':
				break;
			case 'image':
				$media = new CMedia();

				$downloadInfo = $media->downloadImage($payload['picture'], '', pref('[Snsfg]/pathToWechatMedia'), pref('[Snsfg]/WechatMedia/Image'));

				$uploadInfo = $wechat->uploadMedia('@'.$downloadInfo['pathTo'] . $downloadInfo['name'], 'image');
				$uploadInfo = json_decode($uploadInfo, true);

				$media->setType($payload['msgtype']);
				$media->setSourceUrl($payload['picture']);
				$media->setPathTo($downloadInfo['pathTo']);
				$media->setName($downloadInfo['name']);
				$media->setMediaId($uploadInfo['media_id']);
				$media->setCreateTime($uploadInfo['created_at']);
				$media->save();

				$params['image'] = array('media_id'=>$uploadInfo['media_id']);

				break;
			case 'mpvideo':
				break;
			default:
				# code...
				break;
		}
	
		$response = $wechat->callapi('message/mass/sendall', $params, 'POST');
		if(is_array($response))
		{
			$result = $response;
		}
		else
		{
			$result = json_decode($response, true);
		}


		$postStatus = new CPostStatus();

		$postStatus->setAccountId($account->getWechatAppId());

		if(isset($payload['content']))
		{
			$postStatus->setContent($payload['content']);
		}
		else if(isset($payload['articles']))
		{
			$postStatus->setContent(json_encode($payload['articles']));
		}
		
		if($result['errcode'] == 0)
		{
			$postStatus->setInternalId($result['msg_id']);
		}
		else
		{
			$postStatus->setInternalId(0);
			$postStatus->setDiscription($response);
		}

		$postStatus->setUniverse($payload['ef_universe_id']);
		$postStatus->setSendingId($payload['ef_sending_id']);
		$postStatus->setCreatedAt(time());
		$postStatus->setCreatedAt(time());
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->setType($payload['msgtype']);
		$postStatus->save();

		return $response;
	}


	/**
	 *
	 */
	 	
	public function startConnection(&$account)
	{

		$wechat = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());

		$responseJson = $wechat->getAccessToken();
		$response = json_decode($responseJson, true);

		if(isset($response['access_token']) && $response['access_token'])
        {
        	$account->setPrivateApiToken($response['access_token']);
        }
        else
        {
        	$account->setPrivateApiToken($responseJson);
        }

		$account->setIsTemporary(0);
		$account->save();

		return $responseJson;
	}


	/**
	 *
	 */

	public function updateAccount(&$account) {

	}

	/**
	 *
	 */

	public function updateStatus(&$account) {

	}


	/**
	 *
	 */

	public function prepareNews($articles, $account)
	{
		$result = $articles;

		$accessToken = new \WechatToken($account->getWechatAppId(), $account->getWechatAppSecret());
		$responseJson = $accessToken->getAccessToken();
		$accessToken = json_decode($responseJson, true);

		$wechat = new \Wechat($accessToken['access_token']);
		$media = new CMedia();

		foreach ($articles as $key => $article) {

			$downloadInfo = $media->downloadImage($article['picture_url'], '', pref('[Snsfg]/pathToWechatMedia'), pref('[Snsfg]/WechatMedia/Image'));
			
			$uploadInfo = $wechat->uploadMedia('@'.$downloadInfo['pathTo'] . $downloadInfo['name'], 'thumb');

			$uploadInfo = json_decode($uploadInfo, true);

			$article['link'] = str_replace("\"", "'", $article['link']);
			$result[$key]['content_source_url'] = urlencode($article['link']);

			$result[$key]['thumb_media_id'] = $uploadInfo['thumb_media_id'];

			// $result[$key]['author'] = urlencode($article['author']);
			// $result[$key]['title'] = urlencode($article['title']);
			// $result[$key]['content'] = urlencode($article['content']);
			// $result[$key]['digest'] = urlencode($article['digest']);
			$article['author'] = str_replace("\"", "'", $article['author']);
			$article['title'] = str_replace("\"", "'", $article['title']);
			$article['content'] = str_replace("\"", "'", $article['content']);
			$article['digest'] = str_replace("\"", "'", $article['digest']);
			$result[$key]['author'] = urlencode($article['author']);
			$result[$key]['title'] = urlencode($article['title']);
			$result[$key]['content'] = urlencode($article['content']);
			$result[$key]['digest'] = urlencode($article['digest']);

			$media->setType('thumb');
			$media->setSourceUrl($article['picture_url']);
			$media->setPathTo($downloadInfo['pathTo']);
			$media->setName($downloadInfo['name']);
			$media->setMediaId($uploadInfo['thumb_media_id']);
			$media->setCreateTime($uploadInfo['created_at']);
			$media->save();

			$media->reset();

			unset($result[$key]['picture_url']);
			unset($result[$key]['link']);
		}


		return $result;
	}

}

?>
